package com.zmn.oms.admin.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.zmn.common.dto.ResultDTO;
import com.zmn.oms.common.constant.UeditorConstants;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.model.entity.conf.ueditor.Ueditor;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkUploadService;
import org.apache.commons.fileupload.FileUploadException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Objects;

/**
 * 类描述：上传图片
 *
 * @author SongWeidong
 * @date 2019-07-15 14:02
 */
@RestController
@RequestMapping(value = "/oms/uploaderImage")
public class UploaderImageController extends OmsBaseController {

    @Resource
    private OrderWorkUploadService orderWorkUploadService;

    @RequestMapping(value = "/uploader")
    protected ResultDTO uploaderImage(MultipartFile file) {

        String imgUrl;
        try {
            long times = Calendar.getInstance().getTimeInMillis();
            String fileName = orderWorkUploadService.getFileName("oms",times+"");
            imgUrl = orderWorkUploadService.uploaderImage(file, fileName, "oms/oms");
        } catch (FileUploadException e) {
            logger.error(e.getMessage(), e);
            return ResultDTO.resultError("图片上传失败");
        }
        ResultDTO resultSuccess = ResultDTO.resultSuccess("图片上传成功");
        resultSuccess.setId(imgUrl);
        return resultSuccess;
    }


    /**
     *
     * 根据 param 判断【获取 ueditor 的配置】 或 【上传图片】
     *
     * @author liudi
     */
    @RequestMapping(value = "/ueditor")
    public void ueditorUploadImage(@RequestParam("action") String param,
                                   MultipartFile file,
                                   HttpServletResponse response) {
        String utf8 = "UTF-8";
        response.setCharacterEncoding(utf8);
        response.setContentType("application/text;charset=UTF-8");

        try {
	        PrintWriter writer = response.getWriter();

            // 返回ueditor配置
            if (UeditorConstants.UEDITOR_CONFIG_TYPE.equals(param)) {
                writer.write(UeditorConstants.UEDITOR_CONFIG);
                writer.flush();
                writer.close();
                return;
            }

            // 上传图片
            Ueditor ueditor;
            if (UeditorConstants.UEDITOR_UPLOAD_IMAGE_TYPE.equals(param) && Objects.nonNull(file)) {
                ueditor = uploadFile(file);
            } else {
                ueditor = new Ueditor();
                ueditor.setState("文件为空");
            }
            writer.write(JSONObject.toJSONString(ueditor));
            writer.flush();
            writer.close();
        } catch (IOException e) {
	        logger.error(e.getMessage(), e);
        }
    }


    private Ueditor uploadFile(MultipartFile file) {
        Ueditor image = new Ueditor();

        try {
            String originalFilename = file.getOriginalFilename();
            Integer maxImageSize = 5120000;
            if (file.getSize() > maxImageSize) {
                image.setState("Picture is too large,please choose new");
                image.setUrl("none");
                image.setOriginal(originalFilename);
                image.setTitle(originalFilename);
                return image;
            }

            // 图片存储位置
            String directoryName = "oms/conf/ueditor";
            long times = Calendar.getInstance().getTimeInMillis();
            String fileName = orderWorkUploadService.getFileName("ueditor", String.valueOf(times));

            // 上传图片
            String imgUrl = orderWorkUploadService.uploaderImage(file, fileName, directoryName);
            logger.info(" 【UploaderImageController#uploadFile】，图片上传成功，上传路径为 ：" + imgUrl);

            image.setUrl(imgUrl);
            image.setState("SUCCESS");
            image.setOriginal(fileName);
            image.setTitle(fileName);
        } catch (FileUploadException e) {
            logger.error("图片上传失败，失败原因:" + e.getMessage());
            image.setState("FAIL");
        }
        return image;
    }

}
